package lium.lbs.lbsim.fragments

import android.content.Intent
import android.support.v7.widget.LinearLayoutManager
import android.text.TextUtils
import android.view.View
import com.buz.hjcdriver.bean.FriendsModel
import com.buz.hjcdriver.bean.FriendsResultModel
import com.chad.library.adapter.base.BaseQuickAdapter
import com.jakewharton.rxbinding2.widget.RxTextView
import com.lmlibrary.bean.ResponseBean
import com.lzy.okgo.model.Response
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.fragment_friendslist.*
import lium.lbs.lbsim.R
import lium.lbs.lbsim.activity.FriendDetailActivity
import lium.lbs.lbsim.adapter.FriendListAdapter
import lium.lbs.lbsim.listener.ReMarketMessageEven
import lium.lbs.lbsim.utils.CharacterParser
import lium.lbs.lbsim.utils.PinnedHeaderItemDecoration
import lium.lbs.lbsim.utils.callbck.DialogCallback
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.HashMap
import java.util.concurrent.TimeUnit

class FriendListFragment : BaseFragment(), BaseQuickAdapter.OnItemClickListener {


    lateinit var adapter: FriendListAdapter
    private val listData: ArrayList<FriendsResultModel> = arrayListOf()
    var friendAdapterList = arrayListOf<FriendsResultModel>()
    /**
     * 汉字转换成拼音的类
     */
    private var characterParser: CharacterParser? = null

    override fun getLayoutId(): Int {
        if (!EventBus.getDefault().isRegistered(this))
        {
            EventBus.getDefault().register(this);
        }
        return R.layout.fragment_friendslist
    }

    companion object {
        fun newInstance(): FriendListFragment {
            return FriendListFragment()
        }
    }

    override fun initView() {
        characterParser = CharacterParser.getInstance()
        adapter = FriendListAdapter(listData)
        recyclerView.adapter = adapter
        //adapter.disableLoadMoreIfNotFullPage(recyclerView) //关闭BRAVE的自动加载功能 改成 refreshLayout的上拉加载
        adapter.onItemClickListener = this
        val layoutManager = LinearLayoutManager(activity)
        recyclerView.layoutManager = layoutManager
        recyclerView.addItemDecoration(PinnedHeaderItemDecoration())
        refreshLayout.setOnRefreshListener {
            addDisposable(RxTextView.textChanges(this!!.search_myfriends)
                .debounce(200, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .map(CharSequence::toString)
                .subscribe {
                    getDataList(it)
                })
            refreshLayout.finishRefresh()
            refreshLayout.finishLoadMore()
        }
        mSidBar.setTextView(slide_dialog)
        mSidBar.setOnTouchingLetterChangedListener {
            //该字母首次出现的位置
            var position = 0
            for ((index, friend) in adapter.data.withIndex()) {
                if (TextUtils.equals(friend.letters, it.toUpperCase())) { //转为大写后 判断是否相同
                    position = index
                    if ("#" == it) {
                        position = -1 //不处理#
                    }
                    if ("A" == it) {
                        position = 1 //不处理#
                    }

                    break
                }
            }
            if (position != -1 && position != 0) {
                recyclerView.scrollToPosition(position)
                var mLayoutManager = recyclerView.layoutManager as LinearLayoutManager
                mLayoutManager.scrollToPositionWithOffset(position, 0)
            }
        }

        addDisposable(RxTextView.textChanges(this!!.search_myfriends)
            .debounce(200, TimeUnit.MILLISECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .map(CharSequence::toString)
            .subscribe {
                getDataList(it)
            })
    }

    fun getDataList(keywords: String) {
        val param = HashMap<String, String>()
        if (!TextUtils.isEmpty(keywords)) {
            param["keywords"] = keywords
        }
        postData(
            "/frinds/getMyFriendsList",
            param,
            object : DialogCallback<ResponseBean<ArrayList<FriendsResultModel>>>(baseActivity) {
                override fun onSuccess(response: Response<ResponseBean<ArrayList<FriendsResultModel>>>) {
                    setDataList(response.body().data)
                }
            })


    }


    fun setDataList(list: ArrayList<FriendsResultModel>) {
        friendAdapterList.clear()
        if (list != null && !list.isEmpty()) {
            for (friend in list) {
                val pinyin = characterParser!!.getSelling(friend.nickName)
                val sortString = pinyin.substring(0, 1).toUpperCase()
                // 正则表达式，判断首字母是否是英文字母
                if (sortString.matches("[A-Z]".toRegex())) {
                    friend.letters = sortString.toUpperCase()
                } else {
                    friend.letters = "#"
                }
            }
            list.sortBy { it.letters }

            for ((index, bean) in list.withIndex()) {
                if (index == 0) {
                    friendAdapterList.add(
                        0,
                        FriendsResultModel("", "", "", "", bean.letters, FriendsModel.ITEM_TYPE_SETION)
                    )
                    friendAdapterList.add(bean)
                } else {
                    if (TextUtils.equals(list[index - 1].letters, bean.letters)) { //判断上一个item缩写字母和当前的 是否一样
                        friendAdapterList.add(bean)
                    } else {
                        friendAdapterList.add(
                            FriendsResultModel(
                                "",
                                "",
                                "",
                                "",
                                bean.letters,
                                FriendsModel.ITEM_TYPE_SETION
                            )
                        )
                        friendAdapterList.add(bean)
                    }
                }
            }

        } else {
            show_no_friend.visibility = View.VISIBLE
        }
        adapter.data.clear()
        adapter.data.addAll(friendAdapterList)
        adapter.loadMoreComplete()
        adapter.notifyDataSetChanged()
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        val intent = Intent(activity, FriendDetailActivity::class.java)
        intent.putExtra("fid", friendAdapterList[position].friendId)
        activity!!.startActivityForResult(intent,100)
    }

    override fun onClick(v: View?) {
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 100 && resultCode == 200) {
            addDisposable(RxTextView.textChanges(this!!.search_myfriends)
                .debounce(200, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .map(CharSequence::toString)
                .subscribe {
                    getDataList(it)
                })
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun Event(reMarketMessageEven: ReMarketMessageEven) {
        when (reMarketMessageEven.message) {
            2 -> {
                getDataList("")
            }
        }
    }

    override fun onDestroy() {
        EventBus.getDefault().unregister(this)
        super.onDestroy()
    }
}

